package com.gin.kotlin.vegetables_kot.adapter

import android.content.Context
import android.widget.ArrayAdapter
import android.widget.Filter

class OptionAdapter(context: Context, private val options: MutableList<String>? = null) :
    ArrayAdapter<String>(
        context,
        android.R.layout.simple_dropdown_item_1line,
        options ?: listOf()
    ) {

    var filteredList: List<String> = options ?: listOf()

    override fun getCount() = filteredList.size

    override fun getItem(position: Int) = filteredList[position]

    override fun getFilter(): Filter {
        return MyFilter(options, this)
    }

    class MyFilter(
        private val options: MutableList<String>? = null,
        val optionAdapter: OptionAdapter
    ) : Filter() {
        override fun performFiltering(constraint: CharSequence?): FilterResults {
            val filterResults = FilterResults().also {
                it.count = 0
                it.values = listOf<String>()
            }

            constraint?.trim()?.toString()?.also { text ->
                options?.filter { it.contains(text) }?.also { list ->
                    filterResults.count = list.size
                    filterResults.values = list
                }
            }

            return filterResults
        }

        override fun publishResults(constraint: CharSequence?, results: FilterResults?) {
            optionAdapter.filteredList = results!!.values as List<String>
            optionAdapter.notifyDataSetChanged()
        }
    }
}